﻿using System;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Linq;
using Subfaculty.Common.Interfaces;
using Subfaculty.Common.Interfaces.Services;
using System.Transactions;


namespace Subfaculty.Infrastructure.Repositories
{
	public class BaseRepository<T> : IBaseRepository<T> where T: class
	{
		protected ISessionProvider Provider;

		protected ISession Session
		{
			get { return Provider.Session; }
		}

		public BaseRepository(ISessionProvider provider)
		{
			Provider = provider;
		}


		public virtual T Get(int id)
		{
			return Session.Get<T>(id);
		}

		public virtual IEnumerable<T> GetAll()
		{
			return Session.Query<T>();
		}

		public virtual bool Save(T entity)
		{
			try
			{
				using (var scope = new TransactionScope(TransactionScopeOption.Required))
				{
					Session.SaveOrUpdate(entity);
					scope.Complete();
				}
			}
			catch (Exception e)
			{
				throw new Exception(string.Format("Не удалось произвести сохранение данных ({0})", e.Message), e);
			}

			return true;
		}

		public virtual bool Delete(T entity)
		{
			try
			{
				using (var scope = new TransactionScope(TransactionScopeOption.Required))
				{
					Session.Delete(entity);
					scope.Complete();
				}
			}
			catch (Exception e)
			{
				throw new Exception(string.Format("Не удалось удалить элемент ({0})", e.Message), e);
			}

			return true;
		}

		public virtual bool Delete(int id)
		{
			var entity = Get(id);
			if (entity != null) Delete(entity);

			return true;
		}
	}
}
